<template>
  <a-modal
    v-model:open="visible"
    :title="props.isEdit ? '编辑平充时段' : '新增平充时段'"
    @ok="handleOk"
    destroyOnClose
    :width="450"
    @cancel="handleCancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      ref="formRef"
      :labelCol="{
        style: {
          width: '80px',
        },
      }"
    >
      <a-form-item label="省份" name="provId">
        <a-select
          v-model:value="form.provId"
          placeholder="请选择"
          class="formInput"
          show-search
          optionFilterProp="label"
          allow-clear
        >
          <a-select-option
            v-for="item in provinceList"
            :key="item.provId"
            :value="item.provId"
            :label="item.provName"
          >
            {{ item.provName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="平充时段" name="flatTime">
        <a-time-range-picker
          v-model:value="time"
          value-format="HH:mm"
          format="HH:mm"
          showTime
          class="formInput"
          @blur="handleSaveTime"
        />
      </a-form-item>
      <a-form-item label="已选时段">
        <div>
          <a-tag
            class="tagConent"
            v-for="(item, index) in form.flatTime"
            :key="item"
            :closable="!props.isInfo"
            @close="handleCloseDate(index, 'curveCalculationDate')"
            >{{ item }}
          </a-tag>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>

import { isArray, isObject, debounce } from "lodash-es"
const $api = inject("$api")
const props = defineProps({
  addTimeSlotConfigVisible: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
    default: () => {},
  },
})
const visible = ref(props.addTimeSlotConfigVisible)
watch(
  () => props.addTimeSlotConfigVisible,
  (val) => {
    visible.value = val
    if (val) {
      if (val && props.isEdit) {
        form.value = {
          id: props.rowData.id,
          provId: props.rowData.provId,
          flatTime: props.rowData.flatTime
            ? props.rowData.flatTime.split(", ")
            : [],
        }
      } else {
        form.value = {
          provId: null,
          flatTime: [],
        }
      }
    }
  }
)

const emit = defineEmits(["update:addTimeSlotConfigVisible", "success"])
const time = ref([])
const formRef = ref(null)
const form = ref({
  provId: null,
  flatTime: [],
})

const rules = {
  provId: [{ required: true, message: "请选择省份" }],
  flatTime: [
    {
      required: true,
      trigger: "blur",
      validator: (rule, value) => {
        if (form.value.flatTime.length === 0) {
          return Promise.reject("请选择执行时段")
        } else {
          return Promise.resolve()
        }
      },
    },
  ],
}

const provinceList = ref([])
const getProvinceList = async () => {
  let res = await $api.baseProvinceTree()
  if (res && res.code === 0) {
    provinceList.value = res.data
  }
}
const handleSaveTime = () => {
  if (time.value?.length > 0) {
    form.value.flatTime.push(prefixDate(time.value))
    time.value = []
    formRef.value.validateFields("flatTime")
  }
}
const prefixDate = (value) => {
  if (isArray(value)) {
    let date1 = value[0]
    let date2 = value[1]
    return date1 + "-" + date2
  }
  if (isObject(value)) {
    let date1 = value.startTime
    let date2 = value.endTime
    return date1 + "-" + date2
  }
}
const handleCloseDate = (index, type) => {
  form.value.flatTime.splice(index, 1)
}
const handleOk = async () => {
  try {
    await formRef.value.validate()
    emit("success", form.value)
    handleCancel()
  } catch (error) {
    console.error("表单验证失败", error)
  }
}

const handleCancel = () => {
  formRef.value?.resetFields()
  form.value.flatTime = []
  emit("update:addTimeSlotConfigVisible", false)
}
onMounted(() => {
  getProvinceList()
})
</script>

<style scoped>
.formInput {
  width: 90%;
}
.tagConent {
  margin-top: 10px;
}
</style>
